package com.qingmi.farmer.window;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.InputFilter;
import android.widget.EditText;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.qingmi.farmer.R;
import com.wjjun.basemvpvm.utils.RangeInputFilter;
import com.wjjun.basemvpvm.viewmodel.BaseViewModel;
import com.wjjun.customview.window.BaseDialog;

/**
 * 修改数量
 * Created by 67535 on 2018/5/19.
 */
public class EditCountDialog extends BaseDialog {

    private EditText editText;
    private RangeInputFilter rangeInputFilter;

    private double maxCount = 1000000000;
    private double minCount = 1;

    private BaseViewModel baseViewModel;

    public EditCountDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_edit_count;
    }

    public double getMaxCount() {
        return maxCount;
    }

    public void setMaxCount(double maxCount) {
        this.maxCount = maxCount;
        rangeInputFilter.setMaxValue(maxCount);
        editText.setHint(getString(R.string.format_hint_count, maxCount));
    }

    public double getMinCount() {
        return minCount;
    }

    public void setMinCount(double minCount) {
        this.minCount = minCount;
        rangeInputFilter.setMinValue(minCount);
    }

    @Override
    protected void initViews() {
        super.initViews();
        editText = findViewById(R.id.edit_count);
        rangeInputFilter = new RangeInputFilter();
        editText.setFilters(new InputFilter[]{rangeInputFilter});
    }

    public BaseViewModel getViewModel() {
        return baseViewModel;
    }

    public void setViewModel(BaseViewModel baseViewModel) {
        this.baseViewModel = baseViewModel;
    }


    public void setCount(int count) {
        editText.setText(String.valueOf(count));
    }

    @Override
    protected void onConfirm() {
        String counts = editText.getText().toString();
        if (StringUtils.isTrimEmpty(counts)) {
            showToast(R.string.error_count_is_empty);
            return;
        }
        int count = Integer.parseInt(counts);
        if (count <= 0) {
            showToast(R.string.error_count_is_error);
            return;
        }
        if (onDialogListener != null) {
            onDialogListener.onConfirm(count);
        }
    }

    @Override
    public void show() {
        super.show();
        if (editText != null) {
            editText.requestFocus();
            editText.selectAll();
            editText.post(new Runnable() {
                @Override
                public void run() {
                    KeyboardUtils.showSoftInput(editText);
                }
            });
        }
    }
}
